package com.qk.management.service;

import com.qk.entity.Avatar;
import com.qk.common.constants.AvatarMessageConstants;
import com.qk.management.mapper.AvatarMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AvatarCleanupService extends AbstractCleanupService<Avatar> {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private AvatarMapper avatarMapper;

    @Scheduled(cron = "0 0 3 * * ?")
    public void cleanGarbageAvatars() {
        performCleanup();
    }
    
    public void manualCleanGarbageAvatars() {
        log.info(AvatarMessageConstants.MANUAL_CLEANUP_TRIGGERED);
        performCleanup();
    }
    
    @Override
    protected List<Avatar> findExpiredItems() {
        LocalDateTime threeDaysAgo = LocalDateTime.now().minusDays(3);
        return avatarMapper.listGarbageBefore(threeDaysAgo, 1); // GARBAGE状态
    }
    
    @Override
    protected void cleanupItem(Avatar avatar) throws Exception {
        fileStorageService.deleteFile(avatar.getFilePath());
    }
    
    @Override
    protected void handleCleanupError(Avatar avatar, Exception e) {
        log.warn("{}: {}", AvatarMessageConstants.FAILED_TO_DELETE_AVATAR, avatar.getFilePath(), e);
    }
    @Override
    protected void deleteRecords(List<Avatar> avatars) {
        if (!avatars.isEmpty()) {
            List<Long> ids = avatars.stream().map(Avatar::getId).collect(Collectors.toList());
            avatarMapper.deleteBatch(ids);
        }
    }
    @Override
    protected String getTargetType() {
        return "Avatar";
    }
}